package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * projectName: com.atguigu.lease.web.admin.custom.converter
 *
 * @author: 顾司羽
 * time: 2024/12/9 15:55 周一
 * description: 批量制造转化器
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String,T>(){

            @Override
            public T convert(String source) {
                for (T enumConstant : targetType.getEnumConstants()){
                    if (enumConstant.getCode() == Integer.parseInt(source)) {
                        return enumConstant;
                    }
                }
                throw new RuntimeException("非法类型异常!");
            }
        };
    }
}
